
import {Component} from '@angular/core';
import {Platform, IonicPage, NavController, NavParams, AlertController, LoadingController} from 'ionic-angular';
import {Http, Headers, RequestOptions} from '@angular/http';
import {UrlService} from '../../providers/urlService';
import {VersionService} from '../../providers/versionService';
import {IntfService} from '../../providers/intfService';
import {StorageService} from '../../providers/storageService';
import {BackButtonService} from '../../providers/backButtonService';
import { ParamService } from '../../providers/paramService';
import {HttpService} from '../../providers/httpService';
import {FormBuilder, Validators, FormGroup} from '@angular/forms';
import {CommonUtilService} from "../../providers/commonUtilService";
import { Diagnostic } from '@ionic-native/diagnostic';
import { StatusBar } from '@ionic-native/status-bar';
import {UtilService} from "../../providers/utilService";
import { Device } from '@ionic-native/device';
import {ValidService} from "../../providers/validService";
import {TabsTaskPage} from "../tabs-task/tabs-task";

declare var CED: any;

/**
 * Generated class for the Login page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
//  providers: [HttpService, VersionService]
})
export class LoginPage {

  loginForm: FormGroup;
  username: any;
  password: any;
  randomNum: any;
  isRememberPwd: any; //是否记住密码，默认记住。不能用boolean
  localVersion: string;
  num: number = 60;
  smsVerifyCodeInfo: string='获取验证码';
  loading: any; //页面loading框变量
  tapTimes: number = 0; //联通logo点击计数器，点击20次切换测试环境
  env: string; //生产环境还是测试环境标识 prod 或者 test
  iosModelNames:any=["iPhone 6 Plus","iPhone 6"]; //ios 手机类型

  waiting: any;//加载参数

  loginResult = {'isLoginFail': false, 'loginInfo':''}; //登录结果，登录是否失败 , 登录失败提示

  pwshow: boolean = false;

  // loading: any;//加载参数

  constructor(private platform: Platform,
              private navCtrl: NavController,
              private navParams: NavParams,
              private statusBar: StatusBar,
              private alertCtrl: AlertController,
              private loadingCtrl: LoadingController,
              // private this.urlService: this.urlService,
              private versionService: VersionService,
              private intfService: IntfService,
              private storageService: StorageService,
              private backButtonService: BackButtonService,
              private httpService: HttpService,
              // private http2Service: Http2Service,
              // private http3Service: Http3Service,
              //private http4Service: Http4Service,
              private diagnostic: Diagnostic,
              private formBuilder: FormBuilder,
              private device: Device,
              private commonUtil: CommonUtilService,
              public http: Http) {


    //全局初始化操作
    this.initGlobal();

    //初始化登录表单
    this.initLoginForm();
  }

  /**
   * 当页面即将加载时会触发。
   */
  ionViewWillEnter() {
    console.log("login ionViewWillEnter");
  }

  /**
   *  当页面加载完毕时触发。它只会在新页面被创建时触发一次，如页面被缓存再一次触发，它不会有任何反应。
   */
  ionViewDidLoad() {
    console.log("login ionViewDidLoad");
  }


  /**
   * 它的触发和ionViewDidLoad的区别在于，不管是第一次加载还是缓存加载它都会触发
   *
   * 将获取版本号的写在ionViewWillEnter 即将进入页面的方法中
   * 如果写在ionViewDidLoad中 需要足够的加载时间。该方法表示：当页面加载的时候触发，仅在页面创建的时候触发一次，如果被缓存了，那么下次再打开这个页面则不会触发。
   */
  ionViewDidEnter(){
    console.log("login ionViewDidEnter");

    //打开登录页面自动获取上次登录成功的用户名
    this.getLoginUser();

    this.versionService.checkAndUpdateApp(); //检查更新升级
    this.localVersion=this.versionService.localVersion;
  }

  /**
   * 全局初始化操作
   * 1.申请安卓权限
   * 2.改状态栏颜色
   * 3.注册后退按钮事件
   * 申请安卓权限，改状态栏颜色等全局操作，必须放这里执行。
   * 如果放ionViewWillEnter等函数里会出现问题，原因是平台没有准备好就执行，会因为时间差导致比如：diagnostic报未安装，状态栏颜色没改变等问题。
   */
  initGlobal(){
    this.platform.ready().then(() => {
      //注册后退按钮事件
      //这里的 registerBackButtonAction 传了null 进去，回去看看 backButton.service.ts 的判断，我们就可以知道，这里是为了让他能执行双击退出操作
      this.backButtonService.registerBackButtonAction(null);

      //安卓版提前申请权限
      this.questPermission();

      //全局修改 状态栏颜色
      this.changeStatusColor();

      //获取配置文件里的版本号
      this.versionService.getLocalVersion().then((data: string) => {
        this.localVersion = data;
      }).catch((error) => {
      });

    });
  }

  /**
   * 初始化登录表单
   */
  initLoginForm(){
    //ionic2 表单校验, 并且username赋值
    this.loginForm = this.formBuilder.group({
      username: ['', Validators.compose([Validators.minLength(11), Validators.maxLength(11), Validators.required, Validators.pattern("^(13[0-9]|15[0-9]|17[0-9]|18[0-9]|14[57])[0-9]{8}$")])],
      password: [''],
      randomNum: ['', Validators.compose([Validators.required/*, Validators.minLength(6)*/])],
      isRememberPwd: [true, Validators.compose([])]
    });

    //下面必须得关联在一起，不然页面会报错
    this.username = this.loginForm.controls['username'];
    this.password = this.loginForm.controls['password'];
    this.randomNum = this.loginForm.controls['randomNum'];
    this.isRememberPwd = this.loginForm.controls['isRememberPwd']; //默认记住true
  }

  //跳转到首页
  toTabsPage() {
    //TabsPage 首页
    //TabsTaskPage
    this.navCtrl.push('TabsPage', {
    });
  }


  //登录成功后记住用户名, 密码不记录
  saveloginUser(user: any) {
    console.log("saveloginUser user.isRememberPwd:" + user.isRememberPwd);
    //如果记住密码，则保存用户名密码
    if(user.isRememberPwd){
      this.storageService.setLocal('loginUser', {username: user.username/*, password: 'password'*/});
    }
    else{
      this.storageService.setLocal('loginUser', {username: user.username/*, password: 'password'*/});
    }

  }

  //打开登录页面自动获取上次登录成功的用户名
  getLoginUser() {
    let data = this.storageService.getLocal('loginUser');
    //重新赋值给界面input框
    if(data){
      this.loginForm.controls['username'].setValue(data.username);
      this.loginForm.controls['password'].setValue(data.password);
    }
  }

  //登录成功后保存登录成员信息到 sessionStorage，后面接口需要用到
  saveloginUserInfoSession(userInfo: any) {
    return this.storageService.setSession('loginUserInfo', userInfo);
  }

  //登录成功后保存登录成员权限到 sessionStorage，后面接口需要用到
  saveloginUserRightSession(userRight: any) {
    return this.storageService.setSession('loginUserRight', userRight);
  }

  //获取权限
  questPermission(){
    console.log("questPermission");

    //android的权限
    if(this.platform.is("android")){
      //安卓6.0以上需要打开多个运行时权限时，只能使用requestRuntimePermissions。
      //不能单个单个申请，不然会报错A runtime permissions request is already in progress
      //外部存储权限, 访问手机状态权限, 定位权限(乔波的小米5 蓝牙搜索不展示，需要加此权限)
      let permissions =
        [
          this.diagnostic.permission.CAMERA,  //相机权限
          this.diagnostic.permission.WRITE_EXTERNAL_STORAGE, //外部存储权限
          this.diagnostic.permission.READ_PHONE_STATE, //访问手机状态权限
          this.diagnostic.permission.ACCESS_FINE_LOCATION, //精确 定位权限
          this.diagnostic.permission.ACCESS_COARSE_LOCATION, //粗略 定位权限
        ];
      this.diagnostic.requestRuntimePermissions(permissions).then( (statuses) => {
        console.log("requestRuntimePerdepartInfo/queryEparchyListmissions was " + JSON.stringify(statuses));
      }, (error) => {
        console.log("requestRuntimePermissions error " + JSON.stringify(error));
      });
    }

    //ios的权限
    if(this.platform.is("ios")){
      //相册权限
      this.diagnostic.requestCameraRollAuthorization().then( (status) => {
        console.log("CameraRollAuthorization was " + (status == this.diagnostic.permissionStatus.GRANTED ? "granted" : "denied"));
      }, (error) => {
        console.log("CameraRollAuthorization error " + JSON.stringify(error));
      });
    }
  }


  //获取短信验证码
  generateSmsVerifyCode(value) {

    if(ValidService.isPhone(value.username)==false){
      this.commonUtil.showAlert({title:'提示',message:'请先输入正确的手机号码！'});
    }else{
      let generateSmsVerifyCodeParam = ParamService.getGenerateSmsVerifyCodeParam(value);
      this.intfService.getReq(UrlService.url_login_generateSmsVerifyCode(), generateSmsVerifyCodeParam, true).then((data) => {

        console.log("获取短信验证码:"+data.msg);
        if(data.success=="true" ){
          //弹出alert
          this.commonUtil.showToast({
            "message": "短信验证码发送成功",
            "duration":3000,
            "position": "bottom",
            "showCloseButton": false,
            "closeButtonText": "确定",
            "successCallback": () => { }
          });

          //this.getrandomNum = data.randomNum;
        }else{
          this.commonUtil.showAlert({title:'短信验证码失败',message: data.msg});
        }

      }).catch((error) => {
        this.commonUtil.showAlert({title:'获取短信验证码',message:'获取短信验证码其他异常'});
        // this.commonUtil.showAlert("获取短信验证码",'获取短信验证码其他异常');
        console.log("获取短信验证码其他异常");
        // downloading.dismiss();
      });
    }


  }

  //登陆
  login(value) {

    //测试模式直接进入主页
    this.loading =  this.commonUtil.showLoading({'content':'登录中...', 'enableBackdropDismiss':true, 'dismissOnPageChange':true, 'duration':10000});
    var data={Depart_Code:'1509091132486370',User_ID:'1802111748318674',Phone:'15599111788'};
    ParamService.loginUser = data;
    this.saveloginUser(value);
    this.queryMemberTypes(data);
    return;
/*
    let param = ParamService.getLoginParam(value);
    console.log("登陆参数："+JSON.stringify(param));
    if(ValidService.isPhone(value.username)==false){
      this.commonUtil.showAlert({title:'提示',message:'请先输入正确的手机号码！'});
      return;
    }
    if( param.randomNum.length!=6  ){
      this.commonUtil.showAlert({title:'提示',message:'请输入正确的验证码！'});
      return;
    }
    //弹出loadind提示
    this.loading =  this.commonUtil.showLoading({'content':'登录中...', 'enableBackdropDismiss':true, 'dismissOnPageChange':true, 'duration':10000});

    console.log("登陆请求："+UrlService.url_login_submit_hb());

    this.intfService.getReq(UrlService.url_login_submit_hb(), param, true).then((data) => {
      console.log("登陆接口返回"+JSON.stringify(data));

      //关闭loading
      // this.loading.dismiss();

      if (data.success=='true') {
        console.log("登录成功");
        this.saveloginUser(value); //保存用户名到storage
        ParamService.loginUser = data; //保存登录返回的userInfo到 全局变量，后面接口需要
        this.queryMemberTypes(data);
      }
      else {
        this.loginResult.isLoginFail = true;
        this.loginResult.loginInfo = data.msg;
        this.commonUtil.showAlert({title:'登录失败',message:data.msg});
        console.log("登录失败");
        //关闭loading
        this.loading.dismiss();
      }
    }).catch((error) => {
      //关闭loading
      this.loading.dismiss();
    });
*/

  }

  //获取菜单权限
  queryMemberTypes(value) {
    this.toTabsPage();//去首页
    return;
    /*
    console.log('获取菜单权限:queryMemberTypes');
    let memberTypesParam = ParamService.getQueryMemberTypesParam(value);
    this.intfService.getReq(UrlService.url_login_queryMemberTypes(), memberTypesParam, true).then((data) => {
      this.loading.dismiss();
      console.log(JSON.stringify(data));
      ParamService.NavJsonData = data ;//成员类型
      //ParamService.memberType = data['MEMBER_TYPE'];//成员类型
      this.toTabsPage();//去首页
    }).catch((error) => {
      this.loading.dismiss();
      this.commonUtil.showAlert({title:'温馨提示',message:'获取菜单权限异常，请联系管理员处理'});
      // downloading.dismiss();
    });
    */
  }

  /**
   * 全局修改 状态栏颜色
   */
  changeStatusColor(){
    for(let i = 0;i<this.iosModelNames.length;i++){
      //this.platform.is("ios")
      if(UtilService.getIOSMobileModel(this.device.model)==this.iosModelNames[i] || this.platform.is("android")){
        //全局修改 状态栏颜色，参考文章 http://blog.csdn.net/u011127019/article/details/58104056
        this.statusBar.overlaysWebView(false);
        this.statusBar.styleLightContent();
        this.statusBar.backgroundColorByHexString("#36aaf5");
      }else{
        this.statusBar.styleLightContent();
        //全局修改 状态栏颜色，参考文章 http://blog.csdn.net/u011127019/article/details/58104056
        this.statusBar.overlaysWebView(true);
      }
    }

  }

  /**
   * 登录页联通logo点击20次，切换测试环境
   */
  goTest(){
    this.tapTimes++;
    console.log("goTest tapTimes:" + this.tapTimes);

    if(this.tapTimes >= 20){
      UrlService.env = 'test'; //切换测试环境
      this.env = UrlService.env; //用于页面展示
      this.commonUtil.showAlert({title:'环境切换',message:'切换到测试环境'});

    }
  }

  //展示密码
  showPassword(){
    this.pwshow = !this.pwshow;
  }

}
